<template>
  <div class='tinymce-container editor-container'>
    <textarea class='tinymce-textarea' :id="id"></textarea>
    <el-dialog title="选择图片" :modal-append-to-body="true" @close="handleDialogClose" :visible.sync="dialogUploadImageVisible" custom-class="uploadDialog">
      <select-image @on-select-image="handleSelectImage" @on-upload-image="handleUploadImage"></select-image>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogUploadImageVisible = false">确 定</el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script>
    // import { getToken, upload } from 'api/qiniu' // 七牛
    import tinymce from 'tinymce/tinymce'
    import 'tinymce/themes/modern/theme'
    import 'tinymce/plugins/advlist/plugin'
    import 'tinymce/plugins/autolink/plugin'
    import 'tinymce/plugins/code/plugin'
    import 'tinymce/plugins/paste/plugin'
    import 'tinymce/plugins/textcolor/plugin'
    import 'tinymce/plugins/colorpicker/plugin'
    import 'tinymce/plugins/fullscreen/plugin'
    import 'tinymce/plugins/link/plugin'
    import 'tinymce/plugins/lists/plugin'
    import 'tinymce/plugins/media/plugin'
    import 'tinymce/plugins/wordcount/plugin'
    import 'tinymce/plugins/imagetools/plugin'
    import 'tinymce/plugins/image/plugin'
    import 'tinymce/plugins/contextmenu/plugin'
    import 'tinymce/plugins/charmap/plugin'
    import 'tinymce/plugins/print/plugin'
    import 'tinymce/plugins/preview/plugin'
    import 'tinymce/plugins/anchor/plugin'
    import 'tinymce/plugins/searchreplace/plugin'
    import 'tinymce/plugins/visualblocks/plugin'
    import 'tinymce/plugins/insertdatetime/plugin'
    import 'tinymce/plugins/table/plugin'
    import 'tinymce/skins/lightgray/skin.min.css'
    import 'tinymce/skins/lightgray/content.min.css'
    import SelectImage from '../SelectImage'
    import commonApi from '../../api/common'
    export default {
      components: {
        SelectImage
      },
      name: 'tinymce',
      props: {
        id: {
          type: String,
          default: 'tinymceEditor'
        },
        value: {
          type: String,
          default: ''
        },
        toolbar: {
          type: Array,
          required: false,
          default () {
            return ['removeformat undo redo | styleselect | bullist numlist | outdent indent | forecolor | fullscreen code', 'bold italic blockquote | h2 p  media image link | alignleft aligncenter alignright']
          }
        },
        data () {
          return {
            hasChange: false,
            hasInit: false
          }
        },
        menubar: {
          default: ''
        },
        height: {
          type: Number,
          required: false,
          default: 360
        }
      },
      data () {
        return {
          dialogUploadImageVisible: false,
          fileDialogInput: null,
          selectImage: null,
          uploadImage: null
        }
      },
      methods: {
        handleSelectImage (imageData) {
          this.selectImage = imageData
        },
        handleUploadImage (imageData) {
          this.uploadImage = imageData
        },
        handleDialogClose () {
          if (this.selectImage && this.selectImage.fullPath) {
            this.fileDialogInput.value = this.selectImage.fullPath
          } else {
            this.fileDialogInput.value = this.uploadImage ? this.uploadImage.fullPath : ''
          }
        }
      },
      watch: {
        value (val) {
          if (!this.hasChange && this.hasInit) {
            this.$nextTick(() => tinymce.get(this.id).setContent(val))
          }
        }
      },
      mounted () {
        const _this = this
        tinymce.init({
          selector: `#${this.id}`,
          height: this.height,
          skin: false,
          body_class: 'panel-body ',
          object_resizing: false,
          paste_data_images: true,
          language: 'zh_CN',
          language_url: '/static/tinymce/langs/zh_CN.js',
          toolbar: this.toolbar,
          menubar: this.menubar,
          plugins: [
            'advlist autolink lists link image charmap print preview anchor',
            'searchreplace visualblocks code fullscreen',
            'insertdatetime media table contextmenu paste wordcount imagetools'
          ],
          imagetools_toolbar: 'rotateleft rotateright | flipv fliph | editimage imageoptions',
          imagetools_proxy: '/file/proxy',
          end_container_on_empty_block: true,
          powerpaste_word_import: 'clean',
          code_dialog_height: 450,
          code_dialog_width: 1000,
          advlist_bullet_styles: 'square',
          advlist_number_styles: 'default',
          block_formats: '普通标签=p小标题=h2',
          default_link_target: '_blank',
          link_title: false,
          init_instance_callback: editor => {
            if (_this.value) {
              editor.setContent(_this.value)
            }
            _this.hasInit = true
            editor.on('NodeChange Change KeyUp', () => {
              this.hasChange = true
              this.$emit('input', editor.getContent({ format: 'raw' }))
            })
          },
          file_browser_callback_types: 'image',
          file_browser_callback (fieldName, url, type, win) {
            _this.dialogUploadImageVisible = true
            _this.fileDialogInput = win.document.getElementById(fieldName)
          },
          images_upload_handler (blobInfo, success, failure) {
            const formData = new FormData()
            formData.append('type', 'image')
            formData.append('up_file', blobInfo.blob(), blobInfo.filename())
            commonApi.uploadFile(formData).then(response => {
              success(response.data.data.fullPath)
            }, response => {
              _this.$message.error(response.data.data.message)
            })
          },
          setup (editor) {
            editor.addButton('h2', {
              title: '小标题', // tooltip text seen on mouseover
              text: '小标题',
              onclick () {
                editor.execCommand('mceToggleFormat', false, 'h2')
              },
              onPostRender () {
                const btn = this
                editor.on('init', () => {
                  editor.formatter.formatChanged('h2', state => {
                    btn.active(state)
                  })
                })
              }
            })
            editor.addButton('p', {
              title: '正文',
              text: '正文',
              onclick () {
                editor.execCommand('mceToggleFormat', false, 'p')
              },
              onPostRender () {
                const btn = this
                editor.on('init', () => {
                  editor.formatter.formatChanged('p', state => {
                    btn.active(state)
                  })
                })
              }
            })
          }
        })
      },
      destroyed () {
        tinymce.get(this.id).destroy()
      }
    }
</script>

<style scoped>
.tinymce-container {
  position: relative;
}

.tinymce-textarea {
  visibility: hidden;
  z-index: -1;
}

.editor-custom-btn-container {
  position: absolute;
  right: 15px;
  top: 18px;
}

.editor-upload-btn {
  display: inline-block;
}
.uploadDialog ,.el-dialog__wrapper{
  z-index: 200000 !important;
}
</style>
